package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.service.IDepartmentService;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {


    @Autowired
    private DepartmentMapper departmentMapper;



    /**
     * 简单写法
     *
     * @return
     */
//    @Override
//    public List<Department> deptTree() {
//        List<Department> allDepts = departmentMapper.findAll();
//        List<Department> result = new ArrayList<>();
//        // 遍历
//        for (Department dept : allDepts) {
//            if (null == dept.getParentId()) {
//                // 它就是最大的那个die
//                result.add(dept);
//            } else {
//                // 当前的这个dept 是个儿子
//                for (Department parent : allDepts) {
//                    if (parent.getId().equals(dept.getParentId())) {
//                        List<Department> children = parent.getChildren();
//                        children.add(dept);
//                        break;
//                    }
//                }
//            }
//        }
//        return result;
//    }

    /**
     * 你们必会写法
     */
    @Override
    public List<Department> deptTree() {
        List<Department> result = new ArrayList<>();
        List<Department> allDepts = departmentMapper.findAll();
        if (CollectionUtils.isEmpty(allDepts)){
            return result;
        }

        // stream
        Map<Long, Department> parentMap = allDepts.stream().collect(Collectors.toMap(Department::getId, e -> e));
        // 同理
//        Map<Long, Department> parentMap = new HashMap<>();
//        for (Department dept : allDepts) {
//            parentMap.put(dept.getId(),dept);
//        }

        // 遍历
        for (Department dept : allDepts) {
            if (null == dept.getParentId()) {
                // 它就是最大的那个die
                result.add(dept);
            } else {
                // 当前的这个dept 是个儿子
                // 找爹 自己是个儿子 有爹的id
                Department parent = parentMap.get(dept.getParentId());
                if (null == parent){
                    break;
                }
                List<Department> children = parent.getChildren();
                children.add(dept);
            }
        }
        return result;
    }
}
